function Promise (executor) {
    //添加属性
    // [[xx]]表明是对象内置的属性,没法通过js操作
    this.PromiseState = 'pending'
    this.PromiseResult = null
    //声明属性
    this.callbacks = []
    const self = this

    // resolve函数
    function resolve (data) {
        //判断状态是否已经被修改过
        if(self.PromiseState !== 'pending') return
        //1.修改对象状态 (promiseState)
        self.PromiseState = 'fulfilled' //resolved
        //2.设置对象结果值 (promiseResult)
        self.PromiseResult = data
        //调用成功的回调函数

        //异步
        // if(self.callback.onResolved) {
        //     self.callback.onResolved(data)
        // }
        self.callbacks.forEach(item => {
            item.onResolved(data)
        })
    }

    // reject函数
    function reject (data) {
        //判断状态是否已经被修改过
        if(self.PromiseState !== 'pending') return
        //1.修改对象状态 (promiseState)
        self.PromiseState = 'rejected' 
        //2.设置对象结果值 (promiseResult)
        self.PromiseResult = data
        //异步
        // if(self.callback.onRejected) {
        //     self.callback.onRejected(data)
        // }
        self.callbacks.forEach(item => {
            item.onRejected(data)
        })
    }
    //throw 错误时
    try {
        //同步调用 执行器函数
        executor(resolve, reject)
    }   catch(e){
        //修改promise状态为失败
        reject(e)
    }
    
    
    
}

//添加 then 方法

Promise.prototype.then = function (onResolved, onRejected) {

    return new Promise((resolve, reject)=>{
        //调用回调函数 PromiseState
        if(this.PromiseState === 'fulfilled'){
            try{
                //获取回调函数的执行结果
                let result = onResolved(this.PromiseResult)
                //判断
                if(result instanceof Promise) {
                        //如果是 Promise类型 的对象
                        result.then(v=>{
                            resolve(v)
                        },r=>{
                            reject(r)
                        })
                } else {
                    //结果对象状态成功
                    resolve(result)
                }
            }catch(e){
                reject(e)
            }
            
        }
        if(this.PromiseState === 'rejected'){
            onRejected(this.PromiseResult)
        }
        //判断pending状态
        if(this.PromiseState === 'pending'){
            //保存回调函数
            this.callbacks.push({
                onResolved: onResolved,
                onRejected: onRejected
            }) 
        }
    })
}